// pages/goods/list/index.js
import { reqGoodsList } from '@/api/goods'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [], // 商品列表数据
    isFinish: false, // 判断数据是否加载完毕
    total: 0, // 数据总条数
    requestData: {
      page: 1, //页码
      limit: 10, //请求条数
      category1Id: '', //一级分类
      category2Id: '' //二级分类
    },
    isLoading: false
  },
  async getGoodsList() {
    // const { page, limit } = this.data.requestData
    // const res = await reqGoodsList(page, limit, this.data.requestData)
    this.data.isLoading = true

    const res = await reqGoodsList(this.data.requestData)
    this.data.isLoading = false
    // console.log(res)
    const { data } = res
    this.setData({
      goodsList: [...this.data.goodsList, ...data.records],
      total: data.total
    })
  },

  // 监听上拉
  onReachBottom() {
    const { goodsList, total, requestData, isLoading } = this.data
    const { page } = requestData
    if (isLoading) return
    if (goodsList.length === total) {
      this.setData({
        isFinish: true
      })
      return
    }
    // console.log(1)
    // const { page } = this.data.requestData
    this.setData({
      requestData: { ...this.data.requestData, page: page + 1 }
    })
    this.getGoodsList()
  },
  // 下拉
  onPullDownRefresh() {
    this.setData({
      goodsList: [],
      total: 0,
      isFinish: false,
      requestData: { ...this.data.requestData, page: 1 }
    })
    this.getGoodsList()
    wx.stopPullDownRefresh()
  },
  onLoad(option) {
    // console.log(option.category1Id)
    Object.assign(this.data.requestData, option), this.getGoodsList()
  }
})
